import router from "@/router";
import { Notification } from 'element-ui';

let CODE = {
    PONG: 1,
    NOT_LOGIN: -1,
    ACTION : 200,
    ERROR: 50000
}

class Request {
    constructor() {
        this.code;
        this.msg;
        this.data;
        this.seed;
    }
}

class WebSocketUtils{
    constructor() {
        this.url = "ws://localhost:8080/socket";
        this.socket = null;
        this.accpetCallback = null;
    }

    connect() {
        if(typeof(WebSocket) == "undefined") { 
            console.error("浏览器不支持websocket"); 
            return; 
        }
        this.socket = new WebSocket(this.url);
        this.socket.onopen = () => {
            console.log("连接成功");
        }
        this.socket.onmessage = (msg) => {
            if(msg.data) {
                let response = JSON.parse(msg.data);
                switch (response.code) {
                    case CODE.PONG: break
                    case CODE.NOT_LOGIN:
                        Notification.warning("服务器无该登入用户记录, 请重新登录!")
                        router.push("/login")
                        break;
                    case CODE.ACTION:
                        if(this.accpetCallback) {
                            this.accpetCallback(response);
                        }
                        break;
                    case CODE.ERROR:
                        Notification.warning(response.msg);
                        break;
                }
            }
        }
        this.socket.onclose = () => {
            console.log("close websocket");
        }
        this.socket.onerror = () => {
            console.log("websocket on error");
        }
    }

    send(request) {
        if(this.socket == null || this.socket.readyState >= 2) {
            this.connect(this.url);
        }
        else {
            if(typeof(request) == "string") {
                this.socket.send(request);
            }else {
                this.socket.send(JSON.stringify(request));
            }
        }
    }

    heartbeat() {
        if(this.seed) {
            clearInterval(this.seed);
        }

        this.seed = setInterval(() => {
            let request = new Request();
            request.code = 1;
            request.msg = "ping";
            this.send(request)
        }, 5000)
    }

    close() {
        if(this.seed) {
            clearInterval(this.seed);
        }
        this.socket.close();
    }
}

export default new WebSocketUtils();